<?php


class AuthTemplate extends Doctrine_Template
{
	const  AUTH_USER_EXISTS 	 = 1;
	const  AUTH_REGISTER_SUCCESS = 2;
	const  AUTH_ACCESS_DENIED	 = 3;
	const  AUTH_USER_NOT_FOUND   = 4;
	const  AUTH_ACTICODE_INVALID = 5;
	const  AUTH_ACTICODE_VALID	 = 6;
	const  AUTH_LAST_ADMIN_ACCOUNT = 7;
	const  AUTH_PERIOD_INVALID 	 = 8;
	const  AUTH_ADMIN_BLOCK	     = 9;
	const  AUTH_FAKE_USER	     = 10;
	
	private $expiredDays = 365;
	
	private $cookies_name = 'PSP_ID'; 
	
    public function setTableDefinition()
    {
        $this->hasColumn('email', 'string', 50, array('notblank' => true,'EmailFieldValidate' => true));
        $this->hasColumn('password', 'string', 34);
        $this->hasColumn('status', 'integer', 1, array('default' => '0', 'notnull' => true));
        $this->hasColumn('date', 'timestamp', null, array('default' => '0000-00-00 00:00:00', 'notnull' => true));
    }
 
    public function login($email,$password,$option = array())
    {
    	if ($this->isAuthed()){
    		return self::AUTH_REGISTER_SUCCESS;
    	}else{
    		$object = $this->getInvoker();
    	
    		$object_new = $object->getTable()->createQuery()->addWhere("email='".strtolower($email)."'")->fetchOne();

    		if (is_object($object_new))
    		{
				$object->hydrate($object_new->toArray());
				$object->state(Doctrine_Record::STATE_CLEAN);
				if ($this->isBlocked())
				{
					return self::AUTH_PERIOD_INVALID;
				}else{
					if ($this->isBlockedByAdmin()){
						$object->property['Auth_status'] = self::AUTH_ADMIN_BLOCK;
						return self::AUTH_ADMIN_BLOCK;
					}else{
						if ($object->password == $this->encriptPass($password)){
							if ($option['remember']){
								$this->addSessionKey();
							}
							$object->property['Auth_status'] = self::AUTH_REGISTER_SUCCESS; 
							return self::AUTH_REGISTER_SUCCESS;
						}else{
							$object->property['Auth_status'] = self::AUTH_FAKE_USER;
							return self::AUTH_FAKE_USER;
						}
					}	
				}
    		}else{
    			$object->property['Auth_status'] = self::AUTH_USER_NOT_FOUND;
   				return self::AUTH_USER_NOT_FOUND;
    		}
    	}
    }
    
    private function encriptPass($password){
    	return md5($password);
    }
    
	public function isBlockedByAdmin(){
		return false;
	}
	
	public function isAuthed(){
		 $object = $this->getInvoker();
		 if ($object->property['Auth_status'] == self::AUTH_REGISTER_SUCCESS){
		 	return true;
		 }else{
		 	return false;
		 }
	}
	
	public function isBlocked(){
		if (!$this->isAuthed()){
			return false;
		}
		
		$object = $this->getInvoker();
		if ($object->status){
			return false;
		}
		$time=$object->date;
		if (($time+60*60*24)<time()){
			return true;
		}
		return false;
	}
	
	private function addSessionKey(){
		if (!$this->isAuthed()){
			return false;
		}
		
		$object = $this->getInvoker();
		
		$key = Ria_Client::getInstance()->Session->createSessionKey().$object->clientID;
		$expired_date = time()+60*60*24*$this->expiredDays;
		setcookie($this->cookies_name,$key,$expired_date);
			
		return true;
	}
	
	
	public function checkIsLogged() {
		if ($this->isAuthed()){
			return true;
		}
		$key = $_COOKIE[$this->cookies_name];
		$s_key = substr($key,0,64);
		$ClientIDFake = substr($key,64)*1;
		if ($ClientIDFake == 0 || $s_key == ''){
			 return self::AUTH_FAKE_USER;
		}
		$session_db = Doctrine_Query::create()->from('Passport_SessionDBO')->where("sessionKey = '".$s_key."' and clientID = ".$ClientIDFake)->fetchOne();
		if(is_object($session_db)){
			$object = $this->getInvoker();
			$user = $object->getTable()->find($ClientIDFake);
			
			$object->hydrate($user->toArray());
			$object->state(Doctrine_Record::STATE_CLEAN);			
			$this->loginUser();
			return self::AUTH_REGISTER_SUCCESS;
		}
		return self::AUTH_USER_NOT_FOUND;
	}
	
	function logout() {
	 	$_SESSION['person_info']='';
	 	
	 	$key = $_COOKIE[$this->cookies_name];
		$s_key = substr($key,0,64);
		$ClientIDFake = substr($key,64)*1;
		
		Doctrine_Query::create()->delete()->from('Passport_SessionDBO')->where("sessionKey = '".$s_key."' and clientID = ".$ClientIDFake)->execute();
		setcookie($this->cookies_name,'',time());
		
	}
	


}